package com.sz.common.base.dto;

import com.sz.common.base.entity.I18nEntity;
import com.sz.common.base.utils.EntityUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public abstract class I18nBaseDto implements Serializable {
    private Object refId;
    private String language;

    public Serializable getRefId() {
        return (Serializable) refId;
    }

    public void setRefId(Object refId) {
        this.refId = refId;
    }

    public String getLanguage() {
        return language;
    }

    public void setLanguage(String language) {
        this.language = language;
    }

    /**
     * 将国际化对象集合转成I18nEntity对象集合
     *
     * @param dtoList
     * @param tableName
     * @param refId
     * @return
     */
    public static List<I18nEntity> getI18nEntry(List<? extends I18nBaseDto> dtoList, String tableName, Serializable refId) {
        Serializable refReferenceId = refId;

        List<I18nEntity> entityList = new ArrayList<>();
        if (dtoList != null && dtoList.size() > 0) {
            for (I18nBaseDto dto : dtoList) {
                Map<String, Object> beanMap = EntityUtils.transBean2Map(dto);//将要处理的对象转成map集合格式
                if (beanMap.size() > 0) {
                    //取得refId的值
                    if (refId == null || "".equals(refId)) {//当refId没有传递时，从map中取
                        if (beanMap.get("refId") != null && !"".equals(beanMap.get("refId"))) {
                            refReferenceId = (Serializable) beanMap.get("refId");
                        } else {
                            throw new RuntimeException("refId is undefined");
                        }
                    }
                    //组装I18nEntity对象
                    I18nEntity i18nEntity = new I18nEntity(refReferenceId, (String) beanMap.get("language"), tableName);
                    beanMap.remove("refId");
                    beanMap.remove("language");
                    for (Map.Entry<String, Object> entry : beanMap.entrySet()) {
                        i18nEntity.setFieldValue(entry.getKey(), (String) entry.getValue());
                    }
                    //添加I18nEntity对象到集合中
                    entityList.add(i18nEntity);
                }
            }
        }
        return entityList;
    }
}